package util;  
  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;  
  
public class DBConn {  
  
    private static Connection conn;  
  
    private DBConn() {  
  
    }  
  
    public static Connection getConn() {  
        try {  
            if (conn == null) {  
                // 创建集合对象  
                Properties properties = new Properties();  
                // 装载  
                properties.load(DBConn.class.getClassLoader()  
                        .getResourceAsStream("jdbc.properties"));  
                // 加载驱动程序  
                Class.forName(properties.getProperty("driverClassName"));  
                // 获取连接对象  
                conn = DriverManager.getConnection(  
                        properties.getProperty("url"),  
                        properties.getProperty("user"),  
                        properties.getProperty("pass"));  
  
                // 修改事务 为手动提交方式  
                conn.setAutoCommit(false);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        return conn;  
    }  
  
    public static void update(String sql, Object params[],  
            PreparedStatement pstmt) throws Exception {  
        try {  
            pstmt = getConn().prepareStatement(sql);  
            for (int i = 0; i < params.length; i++) {  
                pstmt.setObject(i + 1, params[i]);  
            }  
            pstmt.executeUpdate();  
            conn.commit();  
        } catch (Exception e) {  
            conn.rollback();  
            e.printStackTrace();  
        } finally {  
            release(null, pstmt);  
        }  
    }  
  
    public static void release(ResultSet rs, PreparedStatement pstmt) {  
        if (rs != null) {  
            try {  
                rs.close();  
            } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
        if (pstmt != null) {  
            try {  
                pstmt.close();  
            } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
  
    }  
}  